import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_ERROR, AUTH_CHECK , AUTH_GET_PERMISSIONS} from 'react-admin';

export default (type, params) => {
    // called when the user attempts to log in
    if (type === AUTH_LOGIN) {

        const { username, password } = params;
        const request = new Request(process.env.REACT_APP_AUTH_LOGIN_API, {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        })
        return fetch(request)
            .then(response => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error(response.statusText);
                }
                return response.json();
            })
            .then(({ returnData }) => {
                console.log(returnData)
                const result = returnData.result;
                const username = returnData.username;
                const roles = returnData.roles;
                if(result=="fail"){
                    throw new Error("用户名或密码错误");
                }
                localStorage.setItem('username', username);
                localStorage.setItem('roles', roles);
                
            });
        /*
        const { username } = params;
        localStorage.setItem('username', username);
        localStorage.setItem('role', '["a","b","c"]');
        console.log(localStorage.getItem('role'));
        
        // accept all username/password combinations
       
        */
    }
    // called when the user clicks on the logout button
    if (type === AUTH_LOGOUT) {
        localStorage.removeItem('username');
        return Promise.resolve();
    }
    // called when the API returns an error
    if (type === AUTH_ERROR) {
        const { status } = params;
        if (status === 401 || status === 403) {
            localStorage.removeItem('username');
            return Promise.reject();
        }
        return Promise.resolve();
    }
    // called when the user navigates to a new location
    if (type === AUTH_CHECK) {
        return localStorage.getItem('username')
            ? Promise.resolve()
            : Promise.reject();
    }
    if (type === AUTH_GET_PERMISSIONS) {
        const roles = localStorage.getItem('roles');     
        return roles ? Promise.resolve(roles) : Promise.reject();
    }
    return Promise.reject('Unknown method');
};